package es.deusto.ingenieria.is.gemas;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class GemasXMLParser extends DefaultHandler {
	private List<Gema> gemas;

	public GemasXMLParser(String fileXML) {
		gemas = new ArrayList<Gema>();
		
		this.processXML(fileXML);
	}

	private void processXML(String fileXML) {
		try {
			SAXParserFactory parserFactory = SAXParserFactory.newInstance();
			parserFactory.setValidating(true);
			parserFactory.setNamespaceAware(true);
			SAXParser parser = parserFactory.newSAXParser();
			parser.parse(fileXML, this);
		} catch (Exception ex) {
			System.err.println(this.getClass().getName() + ".parseDocument(): "
					+ ex);
		}
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		try {
			if (qName.equals("is:gem")) {
				String color = attributes.getValue("color");
				int weight = Integer.parseInt(attributes.getValue("weight"));
				String type = attributes.getValue("type");
				Gema g = new Gema(type, color, weight);
				gemas.add(g);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public List<Gema> getGems() {
		return gemas;
	}
	
}
